import os
import win32print
from . import printer_bp  # ✅ 从当前包导入蓝图
from flask import request, render_template, jsonify

# 存储打印作业的目录（用于演示）
PRINT_JOBS_DIR = 'print_jobs'
os.makedirs(PRINT_JOBS_DIR, exist_ok=True)

# 支持的打印选项配置
PRINT_OPTIONS = {
    'page_size': [
        'A4', 'Letter', 'Legal', 'A3', 'A5',
        'B4', 'B5', 'Tabloid', 'Custom'
    ],
    'orientation': ['Portrait', 'Landscape'],
    'color_mode': ['Color', 'Black and White'],
    'quality': ['Draft', 'Normal', 'High', 'Best'],
    'duplex': ['None', 'Long Edge', 'Short Edge'],
    'copies': [str(i) for i in range(1, 21)]
}


# 首页（用于演示）
@printer_bp.route('')
@printer_bp.route('/')
def index():
    printers = get_all_printers()
    print(printers)
    data = {
        'title': '打印机选择',
        'printers': printers,
    }
    return render_template('printer/index.html', **data)  # 模板路径：apps/home/templates/index.html


# 关于（用于演示）
@printer_bp.route('/about')
def about():
    return "printer About Page"


@printer_bp.route('/select_printer/<printer_name>')
def select_printer(printer_name):
    """打印机选择页面"""
    # 验证打印机是否存在
    if printer_name not in get_all_printers():
        return redirect(url_for('index'))

    return render_template('printer/printer_settings.html',
                           printer_name=printer_name,
                           options=PRINT_OPTIONS)


@printer_bp.route('/print_preview', methods=['POST'])
def print_preview():
    """打印预览页面（模拟）"""
    # 获取表单数据
    printer_name = request.form['printer_name']
    page_size = request.form['page_size']
    orientation = request.form['orientation']
    color_mode = request.form['color_mode']
    quality = request.form['quality']
    duplex = request.form['duplex']
    copies = request.form['copies']

    # 验证数据
    if not printer_name:
        return redirect(url_for('index'))

    # 创建打印作业的模拟文件（在实际应用中，会真正打印文档）
    job_id = os.urandom(8).hex()
    job_file = os.path.join(PRINT_JOBS_DIR, f"{job_id}.txt")

    with open(job_file, 'w') as f:
        f.write(f"打印机: {printer_name}\n")
        f.write(f"纸张大小: {page_size}\n")
        f.write(f"方向: {orientation}\n")
        f.write(f"颜色模式: {color_mode}\n")
        f.write(f"打印质量: {quality}\n")
        f.write(f"双面打印: {duplex}\n")
        f.write(f"份数: {copies}\n")

    # 显示打印预览页面（模拟）
    return render_template('printer/print_preview.html',
                           printer_name=printer_name,
                           page_size=page_size,
                           orientation=orientation,
                           color_mode=color_mode,
                           quality=quality,
                           duplex=duplex,
                           copies=copies,
                           job_id=job_id)


@printer_bp.route('/print_job', methods=['POST'])
def print_job():
    """执行打印作业（模拟）"""
    job_id = request.form.get('job_id')
    if not job_id:
        return jsonify(success=False, error="Invalid job ID")

    job_file = os.path.join(PRINT_JOBS_DIR, f"{job_id}.txt")

    # 在实际应用中，这里会有真正的打印代码
    # 例如:
    #   hprinter = win32print.OpenPrinter(printer_name)
    #   win32print.StartDocPrinter(hprinter, 1, ("test", None, "RAW"))
    #   win32print.WritePrinter(hprinter, b"Your document content")
    #   win32print.EndDocPrinter(hprinter)
    #   win32print.ClosePrinter(hprinter)

    # 这里我们只是模拟打印成功
    print(f"模拟打印作业: {job_id}")

    # 删除模拟的打印作业文件
    if os.path.exists(job_file):
        os.remove(job_file)

    return jsonify(success=True)


# 获取所有打印机
def get_all_printers():
    """获取系统所有打印机"""
    printers = []
    for printer in win32print.EnumPrinters(win32print.PRINTER_ENUM_LOCAL, None, 1):
        printer_name = printer[2]
        printers.append(printer_name)
    return printers


# 执行打印
def print_document(printer_name, document_path):
    try:
        # 打开打印机
        hprinter = win32print.OpenPrinter(printer_name)

        # 获取默认打印机设置
        printer_info = win32print.GetPrinter(hprinter, 2)
        devmode = printer_info["pDevMode"]

        # 更新打印设置（使用用户选择的选项）
        # 这里需要根据用户选择更新DEVMODE结构体
        # 例如：设置纸张大小、方向等

        # 开始打印作业
        job_name = "My Document"
        hdc = win32ui.CreateDC()
        hdc.CreatePrinterDC(printer_name)
        hdc.StartDoc(job_name)
        hdc.StartPage()

        # 绘制文档内容（这里只是示例）
        # 实际应用中，可能需要生成PDF或其他格式文档
        hdc.TextOut(100, 100, "This is a test document!")

        hdc.EndPage()
        hdc.EndDoc()

        win32print.ClosePrinter(hprinter)
        return True
    except Exception as e:
        print(f"打印错误: {e}")
        return False
